-- UIScrapMarket
-- Create by huanghr
-- 冈布奥碎片页面

require "game/ui/form/market/UIBuyScrap"

-- UIScrapMarket继承自Layer
UIScrapMarket = class("UIScrapMarket", function()
    return cc.Layer:create();
end);

function UIScrapMarket.create(openType)
    return UIScrapMarket.new(openType);
end

-- 页面类型
local PAGE_TYPE_ACTIVITY = "ActivityShop";   -- 活动碎片购买
local PAGE_TYPE_SKY_SHOP = "SkyPetShop";     -- 天空商店
local PAGE_TYPE_MARKET   = "MarketShop";     -- 商城界面

-- 标签页类型
local TAB_TYPE_CANAS   = 1;   -- 卡纳斯
local TAB_TYPE_AOLUWEI = 2;   -- 奥鲁维
local TAB_TYPE_RANGER  = 3;   -- 游荡者
local TAB_TYPE_ABYSS   = 4;   -- 深渊的咆哮
local TAB_TYPE_ALL     = 5;   -- 全部

-- 标签页顺序
local TAB_ORDER = {
    [TAB_TYPE_ALL]     = 1,
    [TAB_TYPE_AOLUWEI] = 2,
    [TAB_TYPE_CANAS]   = 3,
    [TAB_TYPE_RANGER]  = 4,
    [TAB_TYPE_ABYSS]   = 5,
};

-- 标签页数量
local TAB_NUM = 5;

-- 商品类型
local GOODS_TYPE_ITEM       = 1;   -- 物品
local GOODS_TYPE_SHIP_SKILL = 6;   -- 秘宝

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MIN_GRID_COLUMN = 3;

-- 内部函数声明

-- 构造函数
function UIScrapMarket:ctor(openType)
    -- 初始化
    self:setName("UIScrapMarket");
    local node = cc.CSLoader:createNode("layout/market/ScrapMarket.csb");
    self:addChild(node);
    self.node = node;

    self.openType = openType;
    self.tabType  = TAB_TYPE_ALL;

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.template = template;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 水平滑动，需要显示左右蒙版
    local mask3 = findChildByName(self.template, "mask3");
    mask3:setVisible(true);
    local mask4 = findChildByName(self.template, "mask4");
    mask4:setVisible(true);

    if DungeonM.isInDungeon() and not DungeonM.isPause() then
        -- 迷宫中层级要调高
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 11);
    end

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(2);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化商品格子
    self:initGoodsGrids(self.node);

    -- 绘制标签页
    if self:isShowTab() then
        self:redrawTabs();
    end

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIScrapMarket:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化商品格
function UIScrapMarket:initGoodsGrids(node)
    scrollToTopLeft(self.scrollView);

    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 33;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 163;

    local topHGap  = 100;
    local leftWGap = 20;

    -- 收集商品信息
    local goodsList = self:getGoodsInfo();

    if #goodsList == 0 then
        return;
    end
    -- 商品的共个数
    local shopCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsIcon.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsHorizontal(self, self.scrollView, itemNode, shopCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, leftWGap, self.registerItemTouchEvent);
end

-- 显示活动剩余时间
function UIScrapMarket:updateRemainTime(remainTime)
    if not self.remainTimeLabel and not self.isTick then
        return;
    end

    self.isTick = true;

    local timeDesc = remainingTimeDesc(remainTime);
    timeDesc = string.format(getLocStr("buy_scrap_time"), timeDesc);
    self.remainTimeLabel:setString(timeDesc);

    -- 如果还有剩余，每秒刷新一次
    if remainTime > 0 then
        local function callback()
            self:updateRemainTime(remainTime - 1);
        end
        performWithDelay(self.node, callback, 1.0);
    else
        -- 活动结束了，关掉页面
        UIMgr.getCurrentScene():removeFormByName("UIScrapMarket");
    end
end

-- 绘制标签页
function UIScrapMarket:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tab");

    tabNode:setVisible(true);

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local list = self:getGoodsInfoByCamp();
    local keys = table.keys(list) or {};
    table.sort(keys, function(a, b)
        return TAB_ORDER[a] < TAB_ORDER[b];
    end);

    local j = 1;
    for _, i in ipairs(keys) do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.type = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (j - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");

        tabText:setVisible(false);

        local tabType = i;
        if tabType == self.tabType then
            tabLight:setVisible(true);
            tabImage:loadTexture(getTabIconPath("red"));
            tabIcon:loadTexture(getSmallHeroIconPath("all"));
            tabIcon:setColor(normalColor);
            tabImage:setColor(normalColor);
        else
            tabLight:setVisible(false);
            tabIcon:loadTexture(getCampSmallIconPath(tabType));
            tabIcon:setColor(blendColor);
            tabImage:setColor(blendColor);
        end

        tabNode:addChild(child);
        table.insert(tabNode.rows, child);

        j = j + 1;
    end

    for _, tab in ipairs(tabNode.rows) do
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIScrapMarket:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");

    table.sort(tabNode.rows, function(a, b)
        return TAB_ORDER[a.type] < TAB_ORDER[b.type];
    end);

    -- 带窗口动画播放结束后，页签从上面往下掉
    for i, tab in ipairs(tabNode.rows) do
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.15 * (i - 1));
        local moveDown = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 显示商店
function UIScrapMarket:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.template, "title");
    TextStyleM.setTitleStyle(titleLabel);
    if self.openType == PAGE_TYPE_ACTIVITY then
        titleLabel:setString(getLocStr("buy_slime_scrap_limit"));
    elseif self.openType == PAGE_TYPE_MARKET then
        titleLabel:setString(getLocStr("camp_title_1_" .. self.tabType));
    else
        titleLabel:setString(getLocStr("buy_slime_scrap"));
    end

    -- 提示信息
    local txt1Label = findChildByName(self.template, "subhead");
    TextStyleM.setSubheadStyle(txt1Label);
    if self.openType == PAGE_TYPE_ACTIVITY then
        self.remainTimeLabel = txt1Label;
        local remainTime = ActivityM.getRemainTime(ActivityDungeonM.getCurrentActivityId());
        self:updateRemainTime(remainTime);
    else
        txt1Label:setString(getLocStr("has_bought_slime"));
    end

    -- 获取列表
    local scrapList = self:getGoodsInfo();
    if #scrapList == 0 then
        return;
    end

    -- 显示可购买的冈布奥碎片
    local totalGoodsCount = #scrapList;
    for i = 1, totalGoodsCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local iconImg       = grid:getChildByName("goods_icon");
        local moneyImg      = grid:getChildByName("money_icon");
        local moneyLabel    = grid:getChildByName("money_count");
        local soldOutLabel  = grid:getChildByName("sold_out");
        local rankNode      = grid:getChildByName("star_node");
        local countLabel    =  grid:getChildByName("item_count");
        local tip           = grid:getChildByName("tip");

        if i <= totalGoodsCount then
            grid:setVisible(true);
            local priceType  = scrapList[i][1];   -- 商品支付类型
            local payAttrib  = scrapList[i][2];   -- 支付属性
            local goodsPrice = scrapList[i][3];   -- 商品价格
            local scrapId    = scrapList[i][4];   -- 碎片的ID
            local rank       = scrapList[i][5];   -- 阶位
            local goodsCount = scrapList[i][6];   -- 商品数量
            local goodsId    = scrapList[i][7];   -- 商品ID
            local isSoldOut  = scrapList[i][8];   -- 是否出售完
            local goodsType  = scrapList[i][9];   -- 商品类型

            -- 图标绑定商品ID
            iconImg.goodsId = goodsId;
            iconImg.isSoldOut  = scrapList[i][8];   -- 是否出售完
            iconImg.goodsType  = scrapList[i][9];   -- 商品类型

            if self.openType == PAGE_TYPE_MARKET
                and MarketM.query(goodsId, "classify") == "activity" then
                -- 商城打开(活动限时)
                tip:setVisible(true);
            else
                tip:setVisible(false);
            end

            -- 秘宝不显示
            if goodsType ~= GOODS_TYPE_SHIP_SKILL then
                -- 显示商品阶位
                local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
                if layer then
                    rankNode:removeAllChildren();
                    rankNode:addChild(layer);
                end
            end

            -- 显示商品名称和数量
            TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
            if goodsCount > 1 then
                -- 需要显示数量
                countLabel:setString(tostring(goodsCount));
            else
                countLabel:setVisible(false);
            end

            countLabel:setFontSize(24);

            -- 显示商品图标
            if goodsType == GOODS_TYPE_ITEM then
                local scrapIcon = ItemM.query(scrapId, "icon");
                iconImg:loadTexture(getItemIconPath(scrapIcon));
            elseif goodsType == GOODS_TYPE_SHIP_SKILL then
                local goodsIcon = SkyShipSkillM.query(scrapId, "icon");
                iconImg:loadTexture(getAirShipSkillIconPath(goodsIcon));
            end

            -- 显示价格
            local offset = 0;
            local iconPath;

            -- 属性支付
            if 2 == priceType then
                iconPath = getSmallAttribIconPath(FieldsM.query(payAttrib, "icon"));
                moneyImg:loadTexture(iconPath);
                if payAttrib == "money" then
                    moneyImg:setScale(0.74);
                    offset = -5;
                elseif payAttrib == "gem" then
                    moneyImg:setScale(0.8);
                    offset = -5;
                else
                    moneyImg:setScale(0.55);
                end
            elseif 1 == priceType then
                -- 物品支付
                iconPath = getItemIconPath(ItemM.query(payAttrib, "icon"));
                moneyImg:setScale(0.45);
                moneyImg:loadTexture(iconPath);
            end

            TextStyleM.setTextStyle(moneyLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true);
            moneyLabel:setString(tostring(goodsPrice));
            moneyLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
            if 2 == priceType then
                if ME.user:queryAttrib(payAttrib) < goodsPrice then
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
                else
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
                end
            else
                if ItemM.getAmount(ME.user, payAttrib) < goodsPrice then
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
                else
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
                end
            end

            -- 居中显示
            local moneyImgW = moneyImg:getContentSize().width * moneyImg:getScaleX();
            local moneyLabelW = moneyLabel:getContentSize().width;
            -- 间隔
            local gap = 5;
            local s = (moneyImgW + moneyLabelW + gap) / 2;
            -- 位置调整
            moneyImg:setPositionX(-s - offset / 2 );
            moneyLabel:setPositionX(moneyImg:getPositionX() + offset + moneyImgW + gap);

            -- 中间label隐藏
            soldOutLabel:setVisible(false);


            if isSoldOut then
                -- 背景变灰
                setGrayTransMode(goodsBg, true);
                setGrayTransMode(iconImg, true);

                -- 不显示价格、星星
                moneyImg:setVisible(false);
                moneyLabel:setVisible(false);
                rankNode:setVisible(false);

                -- 显示已出售字样
                soldOutLabel:setVisible(true);
                TextStyleM.setTextStyle(soldOutLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true);
                soldOutLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
                soldOutLabel:setString(getLocStr("has_been_sold"));
            end
        else
            -- 清空多余的格子
            grid:setVisible(false);
        end
    end
end

-- 注册商品点击事件
function UIScrapMarket:registerItemTouchEvent(node)
    -- 点击处理
    local bg = findChildByName(node, "bg");
    local iconImg  = node:getChildByName("goods_icon");
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local goodsId = iconImg.goodsId;
            if MarketM.isSoldOut(goodsId) then
                -- 该商品已售完
                alert(getLocStr("goods_sold_out"));
                AudioM.playFx("market_buy_failed");
                return;
            end

            -- 秘宝
            if iconImg.goodsType == GOODS_TYPE_SHIP_SKILL then
                local info = MarketM.query(goodsId);
                local attrib = table.keys(info["price"])[1];         -- 物品属性
                local value  = table.values(info["price"])[1];       -- 物品价格
                local price = {2, attrib, value};

                local bonusInfo = info["bonus"][1];                  -- 奖励

                local function callback()
                    self:tryBuy(goodsId, 1)
                end

                showGoodsDetail(bonusInfo, price, callback);
                return;
            end

            -- 显示购买界面
            self:openBuyScrapForm(goodsId, 1);
            AudioM.playFx("ui_open1");
        end
    end);
end

-- 注册事件处理回调函数
function UIScrapMarket:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIScrapMarket", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIScrapMarket" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 购买提示
    EventMgr.register("UIScrapMarket", event.BUY_SLIME_SCRAP, function(args)
        self:redraw();

        if "ship_skill" == MarketM.query(args.goodsId, "classify") then
            local bonus = MarketM.query(args.goodsId, "bonus");

            local arr = bonus[1];

            local function delay()
                name = SkyShipSkillM.query(arr[2], "name");
                alert(string.format(getLocStr("buy_goods_done"), name, arr[3]));
            end

            performWithDelay(self, delay, 0.1);
        end
    end);

    -- 活动结束事件
    EventMgr.register("UIScrapMarket", event.ACTIVITY_CLOSE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        if self.openType == PAGE_TYPE_ACTIVITY then
            -- 直接关掉自身
            UIMgr.getCurrentScene():removeFormByName("UIScrapMarket");
        else
            self:redraw();
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIScrapMarket");

            if UIMgr:getCurrentScene():isOpen("UIGainItemPath") then
                local uiForm = UIMgr:getCurrentScene():getFormByName("UIGainItemPath");
                uiForm:redraw();
                uiForm:initData();
            end
            -- 显示商城主界面
            -- 将背景隐藏
            if UIMgr:getCurrentScene():isOpen("UIMarketMain") then
                local uiForm = UIMgr:getCurrentScene():getFormByName("UIMarketMain");
                uiForm:showMarket();
            end
        elseif eventType == "enter" then
            -- 将背景隐藏
            if UIMgr:getCurrentScene():isOpen("UIMarketMain") then
                local uiForm = UIMgr:getCurrentScene():getFormByName("UIMarketMain");
                uiForm:hideMarket();
            end
        end
    end);
end

-- 注册点击事件
function UIScrapMarket:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIScrapMarket");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 注册标签页点击回调
function UIScrapMarket:registerTabTouchEvent(node)
    -- 节点
    local tabImage = node:getChildByName("tab");
    local tabLight = node:getChildByName("light");
    local tabIcon = node:getChildByName("icon");
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 设置当前的分页类型
            self.tabType = node.type;

            -- 去除其它高亮
            for _, tab in ipairs(tabNode.rows) do
                tab:getChildByName("light"):setVisible(false);
                tab:getChildByName("tab"):setColor(blendColor);
                tab:getChildByName("icon"):setColor(blendColor);
            end

            -- 设置本身高亮
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabIcon:setColor(normalColor);

            -- 重绘
            self:initGoodsGrids();
            self:redraw();
        end
    end

    tabImage:addTouchEventListener(onClick);
end

-- 显示购买碎片的页面
function UIScrapMarket:openBuyScrapForm(goodsId, priceType)
    local function callback()
        UIMgr.getCurrentScene():removeFormByName("UIBuyScrap");
        local uiBuyGoods;
        if self.openType == PAGE_TYPE_SKY_SHOP then
            -- 天空商店
            uiBuyGoods = UIBuyScrap.create(goodsId, PAGE_TYPE_SKY_SHOP);
        elseif self.openType == PAGE_TYPE_ACTIVITY then
            -- 活动商店
            uiBuyGoods = UIBuyScrap.create(goodsId, priceType);
        else
            -- 商城商店
            uiBuyGoods = UIBuyScrap.create(goodsId, priceType);
        end
        UIMgr.getCurrentScene():addForm(uiBuyGoods);
    end
    checkIfGuestNeedBind(callback);
end

-- 获取商品的属性表
function UIScrapMarket:getGoodsInfo()
      -- 获取列表
    local ret = {};

    if self.openType == PAGE_TYPE_SKY_SHOP then
        local scrapList = SkyPetShopM.getCanSellScraps();

        if #scrapList == 0 then
            return ret;
        end
        local goodsIndex = 1;
        for _, info in pairs(scrapList) do
            local price = info.scrap_price;
            local priceType = price[1];
            local priceId = price[2];                                       -- 物品的属性
            local priceValue = price[3];                                    -- 物品的价格
            local sellItem = info.sell_scrap;                               -- 出售的物品
            local itemId = sellItem[2];                                     -- 对应碎片的ID
            local rank = ItemM.query(itemId, "rank");                       -- 物品阶位
            local num = sellItem[3];                                        -- 物品的奖励数量
            local goodsId = info.id;
            local isSoldOut = MarketM.isSoldOut(goodsId);
            local goodsType = bonusInfo[1][1];
            if goodsId then
                table.insert(ret, {priceType, priceId, priceValue, itemId, rank, num, goodsId, isSoldOut, goodsType});
                goodsIndex = goodsIndex + 1;
            end
        end
    elseif self.openType == PAGE_TYPE_ACTIVITY then
        local finalList = MarketM.getActivityList(nil, true);
        if #finalList == 0 then
            return ret;
        end

        for _, info in pairs(finalList) do
            local priceType = 2;                                 -- 直接默认为属性
            local attrib = table.keys(info["price"])[1];         -- 物品属性
            local value  = table.values(info["price"])[1];       -- 物品价格
            local bonusInfo = info["bonus"];                     -- 物品的奖励
            local itemId = bonusInfo[1][2];                      -- 物品ID
            local rank = ItemM.query(itemId, "rank");            -- 物品阶位
            local num = bonusInfo[1][3];                         -- 物品的奖励数量
            local goodsId = info["id"];
            local isSoldOut = MarketM.isSoldOut(goodsId);
            local goodsType = bonusInfo[1][1];

            if type(attrib) == "number" then
                -- 是道具
                priceType = 1;
            end

            if info then
                table.insert(ret, {priceType, attrib, value, itemId, rank, num, goodsId, isSoldOut, goodsType});
            end
        end
    else
        local finalList;

        -- 如果当前标签是"全部"类型，那么显示全部
        if self.tabType == TAB_TYPE_ALL then
            finalList = MarketM.getMarketSellScrapList();
        else
            -- 区分阵营
            finalList = MarketM.getMarketSellScrapList(true);
            finalList = finalList[self.tabType];
        end

        for _, info in pairs(finalList) do
            local priceType = 2;                                 -- 直接默认为属性
            local attrib = table.keys(info["price"])[1];         -- 物品属性
            local value  = table.values(info["price"])[1];       -- 物品价格
            local bonusInfo = info["bonus"];                     -- 物品的奖励
            local itemId = bonusInfo[1][2];                      -- 物品ID
            local rank = ItemM.query(itemId, "rank");            -- 物品阶位
            local num = bonusInfo[1][3];                         -- 物品的奖励数量
            local goodsId = info["id"];
            local isSoldOut = MarketM.isSoldOut(goodsId);
            local goodsType = bonusInfo[1][1];

            if type(attrib) == "number" then
                priceType = 1;
            end

            if info then
                table.insert(ret, {priceType, attrib, value, itemId, rank, num, goodsId, isSoldOut, goodsType});
            end
        end
    end

    return ret;
end

-- 尝试购买
function UIScrapMarket:tryBuy(goodsId, amount)
    amount = amount or 1;
    if PAGE_TYPE_SKY_SHOP == self.openType then
        local ret = SkyPetShopM.canBuyScrap(goodsId, amount);
        if ret then
            Operation.cmd_buy_sky_pet_scrap(goodsId, amount);
        end
    else
        local ret = MarketM.canBuySpecialGoods(goodsId, amount)

        if true ~= ret or type(ret) == "string" then
            if "sold_out" == ret then
                 -- 该商品已售完
                showHint(string.format(getLocStr("market_goods_sold_out"), MarketM.query(goodsId, "name")));
            elseif "gem_lack" == ret then
                -- 钻石不足
                showGemLackConfirm();
            elseif type(ret) == "string" then
                -- 有提示语，提示之
                showHint(getLocStr(ret));
            else
                -- 其他原因，统一提示失败
                trace("UIScrapMarket", "购买失败，原因：" .. tostring(ret))
                showHint(getLocStr("market_buy_fail"));
            end
        end

        UIMgr.getCurrentScene():removeFormByName("UIGoodsDetail");

        -- 购买
        Operation.cmd_buy_special_goods(goodsId, amount);
    end
end

-- 是否显示标签页
function UIScrapMarket:isShowTab()
    return self.openType == PAGE_TYPE_MARKET;
end

-- 获取当前标签页的数量
function UIScrapMarket:getTabsCount()
    local goodsInfo = MarketM.getSellScrapList(false, true);

    return sizeof(goodsInfo) + 1;
end

-- 获取分阵营的冈布奥碎片信息
function UIScrapMarket:getGoodsInfoByCamp()
    local campList = MarketM.getSellScrapList(false, true);
    local allList = {[5] = MarketM.getSellScrapList(),};

    return table.add(campList, allList);
end
